package com.haois.mp.database.interceptor;


import com.haois.mp.database.exception.OutException;
import com.haois.mp.database.module.remote.service.IGroupService;
import com.haois.mp.database.module.remote.service.IUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * 登录检查
 */
@Component
public class MpDataInterceptor extends HandlerInterceptorAdapter {

    private static final Logger logger = LoggerFactory
            .getLogger(MpDataInterceptor.class);

    private IUserService iUserService;
    private IGroupService iGroupService;

    public MpDataInterceptor(IUserService iUserService, IGroupService iGroupService) {
        this.iUserService = iUserService;
        this.iGroupService = iGroupService;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws ServletException, IOException, OutException {
        logger.info("微信公众号个人信息完整性检查...");
        String accessToken = (String) request.getAttribute("access_token");

        Map userMap = iUserService.getUserState(accessToken);
        if (userMap == null) {
            throw new OutException("后台服务异常");
        }
        if (!"00".equals(userMap.get("code"))) {
            if ("16".equals(userMap.get("code"))) {
                logger.error("后台服务异常,未能正确返回数据");
                throw new OutException("后台服务异常");
            }
            String url = request.getServletPath();
            request.getRequestDispatcher("/wxmp/user/toDetail?fromPage=" + url)
                    .forward(request, response);
        }
        if (request.getRequestURI().indexOf("/user/info") > 0) {
            return true;
        }
        Map groupMap = iGroupService.getGroupListSize(null, accessToken);
        if (userMap == null) {
            logger.error("后台服务异常,未能正确返回数据");
            throw new OutException("后台服务异常");
        }
        if ("01".equals(groupMap.get("code"))) {
            if ("16".equals(groupMap.get("code"))) {
                throw new OutException("后台服务异常");
            }
            request.getRequestDispatcher("/wxmp/info/noGroup")
                    .forward(request, response);
        }
        request.setAttribute("access_token", accessToken);
        return true;
    }

}
